package com.ruoyi.merchant.service.impl;


import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.mapper.OrderReviewMapper;
import com.ruoyi.merchant.service.IMerchantRatingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 商家评分Service业务层处理
 */
@Slf4j
@Service
public class MerchantRatingServiceImpl implements IMerchantRatingService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private OrderReviewMapper orderReviewMapper;

    /**
     * 计算并更新商家综合评分
     *
     * @param merchantId 商家ID
     * @return 更新后的评分
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal calculateAndUpdateRating(Long merchantId) {
        log.info("开始计算商家评分，商家ID：{}", merchantId);

        // 计算评分
        BigDecimal rating = calculateRating(merchantId);

        // 更新数据库
        int result = merchantMapper.updateMerchantRating(merchantId, rating);
        
        if (result > 0) {
            log.info("商家评分更新成功，商家ID：{}，新评分：{}", merchantId, rating);
        } else {
            log.warn("商家评分更新失败，商家ID：{}，可能商家不存在或已删除", merchantId);
        }

        return rating;
    }

    /**
     * 仅计算商家评分（不更新数据库）
     *
     * @param merchantId 商家ID
     * @return 计算后的评分
     */
    @Override
    public BigDecimal calculateRating(Long merchantId) {
        // 从评价表统计平均分
        BigDecimal avgScore = orderReviewMapper.selectAvgScoreByMerchantId(merchantId);

        // 如果没有评价，返回0分
        if (avgScore == null) {
            log.info("商家暂无评价，商家ID：{}，评分设为0", merchantId);
            return BigDecimal.ZERO;
        }

        // 保留2位小数，四舍五入
        BigDecimal rating = avgScore.setScale(2, RoundingMode.HALF_UP);
        
        // 确保评分在0-5之间
        if (rating.compareTo(BigDecimal.ZERO) < 0) {
            rating = BigDecimal.ZERO;
        }
        if (rating.compareTo(new BigDecimal("5.00")) > 0) {
            rating = new BigDecimal("5.00");
        }

        return rating;
    }

    /**
     * 批量更新所有商家评分（定时任务使用）
     *
     * @return 更新的商家数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateAllMerchantRating() {
        log.info("========== 开始批量更新所有商家评分 ==========");
        long startTime = System.currentTimeMillis();

        // 查询所有有效商家ID
        List<Long> merchantIds = merchantMapper.selectAllActiveMerchantIds();
        log.info("查询到 {} 个有效商家需要更新评分", merchantIds.size());

        int successCount = 0;
        int failCount = 0;

        for (Long merchantId : merchantIds) {
            try {
                calculateAndUpdateRating(merchantId);
                successCount++;
            } catch (Exception e) {
                failCount++;
                log.error("更新商家评分失败，商家ID：{}，错误信息：{}", merchantId, e.getMessage(), e);
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("========== 批量更新商家评分完成 ==========");
        log.info("总商家数：{}，成功：{}，失败：{}，耗时：{}ms", 
                merchantIds.size(), successCount, failCount, (endTime - startTime));

        return successCount;
    }
}
